package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    /**
     * spring为restTemplate注入一个值
     *
     */
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho2(){
        String url = "http://localhost:8081/provider/echo/{msg}";
        return restTemplate.getForObject(url, String.class,123);
    }

    //相比方法3，效率更高
    @Autowired
    private LoadBalancerClient loadBalancerClient;//底层已经创建此对象，不需手动创建
    @Value("${spring.application.name:sca-consumer}")
    private String appName;
    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho1(){
        //String url = "http://localhost:8081/provider/echo/{msg}";
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = String.format("http://%s:%s/provider/echo/%s", host, port, appName);
        return restTemplate.getForObject(url, String.class);
    }

    //效率比较低
    @Autowired
    private RestTemplate loadBalancedRestTemplate;
    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho3(){
        String url = String.format("http://%s/provider/echo/%s","sca-provider",appName);
        return loadBalancedRestTemplate.getForObject(url, String.class);
    }

}
